import React, { Component } from "react";
//import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button";
import { connect } from "react-redux";
import { InputItem, Toast, Modal } from "antd-mobile";
import Banner from "@/views/viewCommon/Banner";
import "./index.scss";
import themeUtil from "@tools/theme";
import verCode from "@component/verCode";
import { InterfaceG } from "@config/Config";
//import BackModal from "@component/backModal/index";
import Notice from "@component/notice/notice";
import yhTools from "@tools/yh";
import { getAppPlatformsDatas } from "@redux/Action/nativeDatas/nativeDatas";

const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkIdCard = value => /(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);
const phoneSeparated = value => {
	let tel = "";
	if (value) {
		tel =
			value.substring(0, 3) +
			" " +
			value.substring(3, 7) +
			" " +
			value.substring(7, 11);
	}
	console.log("2222222", tel);
	return tel;
};
const agreementPageMap = {
	1: "/personalInformationLicense",
	2: "/personalCreditAuthorization"
};
const alert = Modal.alert;
const getDocumentHeight = () => {
	return document.documentElement.clientHeight || document.body.clientHeight;
};
const originalHeight = getDocumentHeight();
@verCode()
@connect(
	state => ({
		bonusStr: state.bankReducer.bonusStr,
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		ocrInfo: state.livenessReducer,
		longitude: state.getAppPlatformsDatas.longitude,
		latitude: state.getAppPlatformsDatas.latitude,
		mobile: state.getAppPlatformsDatas.mobile,
		devicesInfo: state.getAppPlatformsDatas.devicesInfo,
		modal: false
	}),
	dispatch => ({
		_getAppPlatformsDatas: value => dispatch(getAppPlatformsDatas(value))
	})
)
class xhfAddBank extends Component {
	constructor(props) {
		super(props);
		this.state = {
			idNo: "",
			isVisible: false,
			verifyCode: "",
			channelCode: "YHB",
			userBankPhone: props.mobile ? phoneSeparated(props.mobile) : "",
			messageSerialNumber: "",
			verifier: "",
			from: "",
			isBackModalVisible: false,
			hasSendCode: false,
			canSubmit: true,
			spaceID: "",
			inputDisabled: false,
			disablePhone: false,
			showButton: true
		};
	}
	componentWillReceiveProps = nextProps => {
		console.log("nextProps", nextProps.pageParams);
		//props 更新
		const {
			idNo,
			userName,
			inputDisabled,
			disablePhone,
			userBankPhone
		} = nextProps.pageParams;
		if (nextProps.pageParams.inputDisabled) {
			this.setState({
				idNo,
				userName,
				inputDisabled
			});
		}
		if (nextProps.pageParams.disablePhone) {
			this.setState({
				userBankPhone,
				disablePhone
			});
		}
	};

	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		window.removeEventListener("resize", this.resize);
	}
	keyboardEvent = obj => {
		const id = document.activeElement.getAttribute("id");
		if (id !== "fix-cursor") {
			let winHeight = document.documentElement.clientHeight;
			if (document.getElementById(`keybordb_${this.state.spaceID}`)) {
				document.getElementById(`keybordb_${this.state.spaceID}`).style.height =
					(winHeight * obj.heightper) / 2 + 74 + "px";
			}
		}
		if (id === "js-fix-bug") {
			document.activeElement.scrollIntoView();
		}
	};
	componentDidMount = () => {
		// 宝付贷版本用的是YHB 换卡是ll连连, 连连是120s倒计时，华通是60s
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		let _tempRandom = Math.round(Math.random() * 1000000);
		this.setState({
			spaceID: _tempRandom
		});
		window.addEventListener("resize", this.resize);
	};
	resize = () => {
		if (window.innerHeight !== originalHeight) {
			this.setState({
				showButton: false
			});
		} else {
			this.setState({
				showButton: true
			});
		}
	};
	/**获取位置信息*/
	isHasLocation() {
		const _this = this;
		let longitude = this.props.longitude || "";
		let latitude = this.props.latitude || "";
		if (!longitude || !latitude) {
			//获取经纬度
			window.YHAuthorize.callHandler("Privacy_Loaction", "", res => {
				// if (res.status == "1000") {
				const { data = {} } = res;
				longitude = data.longitude || "";
				latitude = data.latitude || "";
				_this.props._getAppPlatformsDatas({
					longitude,
					latitude,
					devicesInfo: {
						...this.props.devicesInfo,
						longitude,
						latitude
					}
				});
				this.xhfAddBank(longitude, latitude);
				// } else if (res.status == "3001") {
				// 	alert("地理位置授权", "允许永辉金融钱包访问您当前的地理位置信息？", [
				// 		{ text: "取消", onPress: () => {} },
				// 		{ text: "设置", onPress: () => this.openLoction() }
				// 	]);
				// } else {
				// 	Toast.info(res.message, 2);
				// }
			});
		} else {
			this.xhfAddBank(longitude, latitude);
		}
	}

	//去设置允许打开地理位置
	openLoction() {
		yhTools.settingPrivacy();
	}

	getMsgCode = () => {
		this.sendMsgCode();
	};

	sendMsgCode = () => {
		const { userName, idNo, userBankPhone, inputDisabled } = this.state;
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		if (!userName) {
			Toast.info("请输入姓名", 2);
			return false;
		}
		if (!idNo) {
			Toast.info("请输入身份证", 2);
			return false;
		}
		if (!inputDisabled && !checkIdCard(submitCardRegexp(idNo))) {
			Toast.info("身份证格式不正确", 2);
			return false;
		}
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(userBankPhone))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(60); //连连验证码时间
		let objs = {
			url: InterfaceG.xhf_credit_threeElementSendCode,
			params: {
				mobilePhone: submitCardRegexp(userBankPhone),
				scene: "threeElement",
				productNo: "601"
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				// Toast.info("验证码30分钟内验证码有效", 2);
				const { orderNo, verifyToken } = res.data;
				this.setState({
					orderNo,
					verifyToken,
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	xhfAddBank = (longitude, latitude) => {
		const { lnid, applyNo, orderNo } = this.props;
		const {
			verifyCode,
			userBankPhone,
			idNo,
			userName,
			verifyToken
		} = this.state;
		if (this.checkCanSubmit(userBankPhone, verifyCode, idNo, userName)) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let params = {
				userName: submitCardRegexp(userName),
				idNo: submitCardRegexp(idNo),
				verifyCode: submitCardRegexp(verifyCode),
				mobilePhone: submitCardRegexp(userBankPhone),
				userDeviceInfo: JSON.stringify(this.props.devicesInfo),
				productNo: "601",
				scene: "threeElement",
				longitude,
				latitude,
				applyNo,
				orderNo,
				verifyToken,
				lnid
			};
			if (verifyToken) {
				this.props.Submit(params);
			} else {
				Toast.info("请先获取验证码", 2);
			}
			this.setState({
				canSubmit: true
			});
		}
	};
	InputOnChange = (key, value) => {
		console.log(key, value);
		this.setState({
			[key]: value
		});
	};
	checkCanSubmit = (phoneNum, verifyCode, idNo, userName) => {
		if (this.state.inputDisabled) {
			return true;
		} else {
			if (!userName) {
				Toast.info("请输入姓名", 2);
				return false;
			}
			if (!idNo) {
				Toast.info("请输入身份证", 2);
				return false;
			}
			if (!checkIdCard(submitCardRegexp(idNo))) {
				Toast.info("身份证格式不正确", 2);
				return false;
			}
			if (!phoneNum) {
				Toast.info("请填写手机号", 2);
				return false;
			}
			if (!checkPhoneReg(submitCardRegexp(phoneNum))) {
				Toast.info("手机号格式不正确", 2);
				return false;
			}
			if (!this.state.hasSendCode) {
				Toast.info("请获取验证码", 2);
				return false;
			}
			if (!verifyCode.length) {
				Toast.info("请输入验证码");
				return false;
			}
			if (verifyCode.length !== 6) {
				Toast.info("验证码输入错误");
				return false;
			}
			return true;
		}
	};

	saveBank = () => {
		this.isHasLocation();
	};

	//查看协议
	openContract = type => {
		const { userName, idNo } = this.props.ocrInfo;
		const year = new Date().getFullYear();
		const month = new Date().getMonth() + 1;
		const day = new Date().getDate();
		const commonParams = {
			personName: userName,
			idCardCode: idNo,
			year,
			month,
			day
		};
		const paramsHuaTong = {
			...commonParams,
			signName: userName
		};
		this.props.history.push({
			pathname: agreementPageMap[type],
			params: type === "huaTongAccount" ? paramsHuaTong : commonParams
		});
	};
	render() {
		const {
			userBankPhone,
			hasSendCode,
			idNo,
			userName,
			inputDisabled,
			disablePhone,
			showButton
		} = this.state;
		const { bonusStr } = this.props;
		const { countDown, isClick } = this.props.verCode;
		return (
			<div className="add-bank-containers-warpper">
				<div className="add-bank-containers">
					{/* 如果派券活动奖励为空字符串则不显示，默认空字符串 */}
					{bonusStr && <Notice noticeContent={bonusStr} />}
					{themeUtil.getTheme() == "yhLife" && (
						<Banner
							className="header-img"
							bannerList={
								this.props.pageParams ? this.props.pageParams.bannerList : []
							}
							history={this.props.history}
						/>
					)}
					{themeUtil.getTheme() == "yhLife" && (
						<div className="progress-container">
							<p className="progress-title">
								已填写 <em>80%</em> 最高5万元信用额度
							</p>
							<div className="progress-bg">
								<span className="progress-line"></span>
							</div>
						</div>
					)}
					<InputItem
						className="my-input"
						value={userName}
						disabled={inputDisabled}
						placeholder="请输入姓名"
						maxLength={10}
						id="js-fix-bug"
						onChange={this.InputOnChange.bind(this, "userName")}
					>
						姓名
					</InputItem>
					<InputItem
						clear
						maxLength={18}
						type="text"
						id="js-fix-bug"
						placeholder="请输入身份证号码"
						value={idNo}
						disabled={inputDisabled}
						className="my-input"
						onChange={this.InputOnChange.bind(this, "idNo")}
					>
						身份证号码
					</InputItem>
					<InputItem
						clear
						type="phone"
						id="js-fix-bug"
						placeholder="请填写预留手机号"
						value={userBankPhone}
						disabled={disablePhone}
						className="my-input"
						onChange={this.InputOnChange.bind(this, "userBankPhone")}
					>
						预留手机号
					</InputItem>
					<InputItem
						clear
						placeholder="请输入验证码"
						maxLength={6}
						minLength={6}
						id="js-fix-bug"
						pattern="[0-9]{6}"
						type="tel"
						className="my-input my-clear2"
						onChange={this.InputOnChange.bind(this, "verifyCode")}
					>
						验证码
						<span className="get-code" onClick={this.getMsgCode}>
							{/* {isClick ? "获取验证码" : countDown} */}

							{isClick ? (hasSendCode ? "重新发送" : "获取验证码") : countDown}
						</span>
					</InputItem>
				</div>
				{showButton && (
					<div className="button-wrapper">
						<div className="agree-wrapper">
							<span className="multi-line">
								<p className="huise">点击按钮，表示您已阅读并同意</p>
								<p className="xieyi-p">
									<a className="xieyi" onClick={() => this.openContract("1")}>
										《个人信息授权书》
									</a>
									<a className="xieyi" onClick={() => this.openContract("2")}>
										《个人征信授权书》
									</a>
								</p>
							</span>
						</div>
						<Button style={{ marginTop: "0.2rem" }} onClick={this.saveBank}>
							{"确定绑定"}
						</Button>
						<div id={"keybordb_" + this.state.spaceID}></div>
					</div>
				)}
			</div>
		);
	}
}
export default xhfAddBank;
